package com.yanq.liancar.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.FindCommentAdapter;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.FindCommentTwoBean;
import com.yanq.liancar.bean.NewsDetailsBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewsDetailsActivity extends BaseToolbarActivity {
    @BindView(R.id.et_pinglun)
    EditText etPinglun;
    @BindView(R.id.img_dianzan)
    ImageView imgDianzan;
    @BindView(R.id.img_shoucang)
    ImageView imgShoucang;
    @BindView(R.id.img_fenxiang)
    ImageView imgFenxiang;
    @BindView(R.id.tv_num)
    TextView tv_num;
    @BindView(R.id.tv_whole)
    TextView tv_whole;
    @BindView(R.id.news_details_root)
    RelativeLayout news_details_root;
    @BindView(R.id.news_details_scroll)
    NestedScrollView news_details_scroll;
    @BindView(R.id.comment_recyclerview)
    RecyclerView comment_recyclerview;
    @BindView(R.id.webView)
    WebView mWebView;
    private int newsId, type;
    private boolean isDianzan, isGuanzhu;
    private Handler handler;
    private List<FindCommentTwoBean.DataBean> mDataBeanList = new ArrayList<>();
    private FindCommentAdapter mFindCommentAdapter;
    private InputMethodManager manager;//输入法管理器


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setStatusBar(this, true, false);
        setContentView(R.layout.activity_newsdetails);
        mTvTitle.setText("发现详情");
        ButterKnife.bind(this);

        newsId = getIntent().getIntExtra("newsId", 0);
        type = getIntent().getExtras().getInt("type");

        LogUtils.e("newsId====", newsId + "");
        initOkGo();

        //type==2为列表评论跳转过来的
        if (type == 2) {
            showSoftInputFromWindow(this, etPinglun);
        }

//        //监听etPinglun获取焦点状态
//        etPinglun.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View view, boolean b) {
//                LogUtils.e("11111111110", b + "");
//                if (b) {
//                    news_details_scroll.fullScroll(ScrollView.FOCUS_DOWN);
//                } else {
//                    //                    et_down.setVisibility(View.GONE);
//                }
//            }
//        });
        getComment(newsId);
        initRecyclerview();

        manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

        etPinglun.setInputType(EditorInfo.TYPE_CLASS_TEXT);
        etPinglun.setImeOptions(EditorInfo.IME_ACTION_SEND);

        etPinglun.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {

                if (i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    //先隐藏键盘
                    if (manager.isActive()) {
                        manager.hideSoftInputFromWindow(etPinglun.getApplicationWindowToken(), 0);
                    }
                    //自己需要的操作
                    if (!TextUtils.isEmpty(etPinglun.getText().toString().trim())){
                        setComment();
                    }
                }
                return false;
            }
        });
    }

    private void initRecyclerview() {

        comment_recyclerview.setNestedScrollingEnabled(false);
        comment_recyclerview.setLayoutManager(new LinearLayoutManager(this));
        mFindCommentAdapter = new FindCommentAdapter(this, mDataBeanList);
        comment_recyclerview.setAdapter(mFindCommentAdapter);
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @OnClick({R.id.img_dianzan, R.id.img_shoucang, R.id.img_fenxiang,R.id.tv_num,R.id.tv_whole})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_dianzan:
                isDianzan = !isDianzan;
                if (isDianzan) {
                    imgDianzan.setImageResource(R.mipmap.dianzan1);
                } else {
                    imgDianzan.setImageResource(R.mipmap.dianzan);
                }
                initDianzan(newsId);
                break;
            case R.id.img_shoucang:
                isGuanzhu = !isGuanzhu;
                if (isGuanzhu) {
                    imgShoucang.setImageResource(R.mipmap.find_guanzhu1);
                } else {
                    imgShoucang.setImageResource(R.mipmap.find_guanzhu);
                }
                initGuanzhu(newsId);
                break;
            case R.id.img_fenxiang:
                PopWinShare popWinShare = new PopWinShare(mContext, news_details_scroll);
                popWinShare.showAtLocation(news_details_root, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.tv_num:
            case R.id.tv_whole:
                Bundle bundle=new Bundle();
                bundle.putInt("newsid",newsId);
                RxActivityTool.skipActivity(mContext, WholeCommentActivity.class,bundle);
                break;

        }
    }

    private void initOkGo() {
        OkGo.<String>post(Config.s + "llc/api/selectCommentsAll")
                .tag(this)
                .params("newsid", newsId)
                .params("token", UserBean.getcToken(mContext))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        NewsDetailsBean bean = gson.fromJson(response.body(), NewsDetailsBean.class);
                        if (bean.isIsSuccess()) {
                            String js = "<script type=\"text/javascript\">"+
                                    "var imgs = document.getElementsByTagName('img');" + // 找到img标签
                                    "for(var i = 0; i<imgs.length; i++){" + // 逐个改变
                                    "imgs[i].style.width = '100%';" + // 宽度改为100%
                                    "imgs[i].style.height = 'auto';" +
                                    "}" + "</script>";
                            mWebView.loadDataWithBaseURL(null,bean.getData().getNewscontent()+js,  "text/html", "UTF-8", null);
                            tv_num.setText(bean.getData().getNewscommentnum()+"条");
                            if (bean.getData().getIftop() == 1) {
                                imgDianzan.setImageResource(R.mipmap.dianzan1);
                                isDianzan = true;
                            } else {
                                imgDianzan.setImageResource(R.mipmap.dianzan);
                                isDianzan = false;
                            }
                            if (bean.getData().getAttention() == 1) {
                                imgShoucang.setImageResource(R.mipmap.find_guanzhu1);
                                isGuanzhu = true;
                            } else {
                                imgShoucang.setImageResource(R.mipmap.find_guanzhu);
                                isGuanzhu = false;
                            }
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }
                    }
                });
    }

    //点赞，取消点赞
    private void initDianzan(int newsId) {
        OkGo.<String>post(Config.s + "llc/api/insert_likes")
                .tag(this)
                .params("newsid", newsId + "")
                .params("token", UserBean.getcToken(this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        //                        FindBean bean = gson.fromJson(response.body(), FindBean.class);
                        //                        if (bean.isIsSuccess()){
                        //                            mItemList.addAll(bean.getData());
                        //                            mFindAdapter.notifyDataSetChanged();
                        //                        }else {
                        //                            RxToast.error(bean.getOutputMessage());
                        //                        }
                    }
                });
    }

    //关注，取消关注
    private void initGuanzhu(int newsId) {
        OkGo.<String>post(Config.s + "llc/api/insert_attention")
                .tag(this)
                .params("newsid", newsId + "")
                .params("token", UserBean.getcToken(this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        //                        FindBean bean = gson.fromJson(response.body(), FindBean.class);
                        //                        if (bean.isIsSuccess()){
                        //                            mItemList.addAll(bean.getData());
                        //                            mFindAdapter.notifyDataSetChanged();
                        //                        }else {
                        //                            RxToast.error(bean.getOutputMessage());
                        //                        }
                    }
                });
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    //获取评论
    private void getComment(int newsId) {
        OkGo.<String>post(Config.s + "llc/api/selectCommentsReply")
                .tag(this)
                .params("newsid", newsId + "")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        FindCommentTwoBean bean = gson.fromJson(response.body(), FindCommentTwoBean.class);
                        if (bean.isIsSuccess()) {
                            if (bean.getCode()==200){
                                mDataBeanList.clear();
                                mDataBeanList.addAll(bean.getData());
                                mFindCommentAdapter.notifyDataSetChanged();
                            }else {
                                //RxToast.normal(bean.getOutputMessage());
                            }
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }
                    }
                });
    }

    //发送评论
    private void setComment(){
        OkGo.<String>post(Config.s + "llc/api/comments_reply")
                .tag(this)
                .params("commentsid",  0)
                .params("newsid", newsId )
                .params("token", UserBean.getcToken(this) )
                .params("commentcontent",etPinglun.getText().toString().trim())
                .params("replytype", 0)
                .params("objectid",  0)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean=gson.fromJson(response.body(),BaseBean.class);
                        if (baseBean.isIsSuccess()){
                            etPinglun.setText("");
                            RxToast.success(baseBean.getOutputMessage());
                        }
                    }
                });
    }
}
